import 'dart:convert';

import 'package:get/get.dart';
import 'package:largefriends/entity/entities/lf_match_filter_entity.dart';
import 'package:largefriends/service/manager/lf_event_helper.dart';
import 'package:largefriends/service/lf_auth_service.dart';

import '../../events/change_filter_event.dart';
import 'lf_store_helper.dart';

class LfSearchFilterHelper {
  LfAuthService authService = Get.find();

  static final LfSearchFilterHelper _singleton =
      LfSearchFilterHelper._internal();

  factory LfSearchFilterHelper() => _singleton;

  LfMatchFilterEntity? _matchFilterEntity;

  LfSearchFilterHelper._internal() {
    getSearchFilter();
  }

  LfMatchFilterEntity getSearchFilter() {
    if (_matchFilterEntity == null) {
      var cache = LfStorageManager.getString(
          '${authService.currentAccount?.userId}_filter');
      if (cache != null && cache.isNotEmpty) {
        _matchFilterEntity = LfMatchFilterEntity.fromJson(_parseData(cache));
      }

      if (_matchFilterEntity != null) {
        if (authService.currentAccount!.isGold() == false) {
          ///非gold了就还原
          _matchFilterEntity!.religion = 0;
          _matchFilterEntity!.smoke = 0;
          _matchFilterEntity!.ethnicity = 0;
          _matchFilterEntity!.distance = 7;
          _matchFilterEntity!.searchOrder = '5';
          saveMatchFilter(_matchFilterEntity!);
        }
      } else {
        _matchFilterEntity = LfMatchFilterEntity(
          maxAge: authService.currentAccount?.matchAge?.max ?? 99,
          minAge: authService.currentAccount?.matchAge?.min ?? 40,
          gender: authService.currentAccount?.matchGender ?? 3,
          // locationEntity: LocationEntity(
          //   countryId: authService.currentAccount?.location?.countryId,
          //   country: authService.currentAccount?.location?.country,
          //   stateId: authService.currentAccount?.location?.stateId,
          //   state: authService.currentAccount?.location?.state,
          //   // cityId: authService.currentAccount?.location?.cityId,
          //   // city: authService.currentAccount?.location?.city,
          // )
        );
      }
    }
    return _matchFilterEntity!;
  }

  void saveMatchFilter(LfMatchFilterEntity matchFilterEntity) {
    _matchFilterEntity = matchFilterEntity;
    LfStorageManager.putString('${authService.currentAccount?.userId}_filter',
        matchFilterEntity.toString());
    LfEventHelper()
        .getEvent()
        .fire(ChangeFilterEvent(ChangeFilterAction.search));
  }

  Map<String, dynamic> _parseData(String data) {
    return json.decode(data) as Map<String, dynamic>;
  }

  void clear() {
    _matchFilterEntity = null;
  }
}
